//
//  ActiveViewController.m
//  LoveCar
//
//  Created by Xue Senhong on 15/5/21.
//  Copyright (c) 2015年 薛森鸿. All rights reserved.
//

#import "ActiveViewController.h"
#import "ActivityCell.h"
#import "ActivityModel.h"
#import "MJRefresh.h"
#import "MJRefreshHeaderView.h"
#import "MJRefreshFooterView.h"
#import "ActivityDetailView.h"
#import "CutPriceViewController.h"
#import "Test.h"
#import <Masonry/Masonry.h>

@interface ActiveViewController ()<UITableViewDataSource, UITableViewDelegate, ConnecBack>

@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) UITableView *table;

@end

@implementation ActiveViewController

- (void)dealloc
{
    [_sendMess release];
    [_area release];
    [_array release];
    [_table release];
    [super dealloc];
}
- (void)awakeFromNib
{
    [super awakeFromNib];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.array = [NSMutableArray array];
    self.pageCount = 2;
    [self step];
    [self createTable];
    [self setupRefresh];
}
- (void)step
{
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.translucent = NO;
    UIView *title = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    [self.navigationItem setTitleView:title];
    [title release];
    
    UIButton *a = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 30)];
    [a setTitle:@"活动" forState:UIControlStateNormal];
    [a setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [title addSubview:a];
    
    UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(80, 0, 70, 30)];
    [b setTitle:@"降价" forState:UIControlStateNormal];
    [b setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    b.titleLabel.font = [UIFont systemFontOfSize:14];
    [b addTarget:self action:@selector(CutPriceAction) forControlEvents:UIControlEventTouchUpInside];
    [title addSubview:b];
    [b release];
    
    
    self.area = [[UIBarButtonItem alloc] initWithTitle:@" 定位中..." style:UIBarButtonItemStylePlain target:self action:@selector(areaAction)];
    self.area.tintColor = [UIColor blueColor];
    self.navigationItem.leftBarButtonItem = _area;
    Test *t = [[Test alloc] init];
    t.delegate = self;
    [t startConnection];
    [_area release];
    
    
}
- (void)areaAction
{
    Test *t = [[Test alloc] init];
    t.delegate = self;
    [t startConnection];
    [t release];
    
}
- (void)connection:(NSString *)str
{
    self.area.title = [NSString stringWithFormat:@" %@", str];
    self.area.tintColor = [UIColor redColor];
    NSLog(@"---%@", str);
}
- (void)CutPriceAction
{
    CutPriceViewController *cutprice = [[CutPriceViewController alloc] init];
    [self.navigationController pushViewController:cutprice animated:YES];
    [cutprice release];
}
// 创建table
- (void)createTable
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 49) style:UITableViewStylePlain];
    _table.delegate = self;
    _table.dataSource = self;
    
    [self.table registerClass:[ActivityCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_table];
    
    [_table setScrollsToTop:YES];
    //_table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_table release];
}
// 更新cell
- (void)reloadDataForCell
{
    NSString *str = @"http://app.api.autohome.com.cn/autov4.0/mobile/activitylist-a2-pm1-v4.0.0-c210200-p1-s20.html";
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    __block ActiveViewController *activeViewController = self;
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDic = [dic objectForKey:@"result"];
        [activeViewController.array removeAllObjects];
        for (NSDictionary *sdic in [dataDic objectForKey:@"activitylist"]) {
            ActivityModel *model = [[ActivityModel alloc] init];
            [model setValuesForKeysWithDictionary:sdic];
            [activeViewController.array addObject:model];
        }
        [activeViewController.table reloadData];
        [activeViewController.table headerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.table addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.table headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.table addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    
    [self reloadDataForCell];

}

- (void)footerRereshing
{
    NSString *str = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.0/mobile/activitylist-a2-pm1-v4d0.0-c210200-p%ld-s20.html", (long)self.pageCount];
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    __block ActiveViewController *activeViewController = self;
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDic = [dic objectForKey:@"result"];
        for (NSDictionary *sdic in [dataDic objectForKey:@"activitylist"]) {
            ActivityModel *model = [[ActivityModel alloc] init];
            [model setValuesForKeysWithDictionary:sdic];
            [activeViewController.array addObject:model];
        }
        activeViewController.pageCount += 1;
        [activeViewController.table reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.table reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.table footerEndRefreshing];
    });
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 290;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    ActivityModel *model = [self.array objectAtIndex:indexPath.row];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:model.imgpath]];
    cell.alabel.text = model.title;
    cell.blabel.text = [NSString stringWithFormat:@"上市时间: %@ | %@ ⭐️", model.pubtime, model.cityname];
    self.sendMess = model.url;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ActivityModel *model = [self.array objectAtIndex:indexPath.row];
    ActivityDetailView *detail = [[ActivityDetailView alloc] init];
    detail.url = model.url;
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
}
// 分割线前移
-(void)viewDidLayoutSubviews
{
    if ([_table respondsToSelector:@selector(setSeparatorInset:)]) {
        [_table setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([_table respondsToSelector:@selector(setLayoutMargins:)]) {
        [_table setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

@end
